package o3rome;

/**
 * @author shkstart
 * @create 2021-12-28-15:04
 */

/*
*
* 罗马数字转阿拉伯数字
*
* */
public class Rome02 {

    public static void main(String[] args) {
        int number = romanToInt("MCMXCIV");
        System.out.println(number);
    }

    public static int romanToInt(String roman) {
        int num = 0;

        int sum = 0;

        int preNum = getValue(roman.charAt(0));

        for (int i = 1; i < roman.length(); i++) {

            num = getValue(roman.charAt(i));

            // 后一位比前一位大，执行减法操作
            if (preNum < num) {
                sum -= preNum;
            } else {
                sum += preNum;
            }
            preNum = num;
        }
        // 处理最后一位
        sum += preNum;
        return sum;
    }

    private static int getValue(char ch) {
        switch (ch) {
            case 'I':
                return 1;
            case 'V':
                return 5;
            case 'X':
                return 10;
            case 'L':
                return 50;
            case 'C':
                return 100;
            case 'D':
                return 500;
            case 'M':
                return 1000;
            default:
                return 0;
        }
    }

}
